package com.lottery.htbc.job;

import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.lottery.htbc.dto.ConfigTaskDto;
import com.lottery.htbc.dto.UserBetConfigDto;
import com.lottery.htbc.service.JspkServiceImpl;
import com.lottery.htbc.service.LuckDrawServiceImpl;
import com.lottery.htbc.thread.LuckDrawJspkeRunnable;
import com.lottery.htbc.utils.service.redis.RedisService;

public  class HtbcLuckDrawJspkJob  {

	private final static Logger LOGGER = LoggerFactory.getLogger(HtbcLuckDrawJspkJob.class);

	/**
	 * 一秒对应的毫秒值
	 */
	private  static  final  long  second=1000L;

	/**
	 * 每天开始时间
	 */
	private  static   final  int BIEGIN_HOUR=4;

	/**
	 * 每天结束时间
	 */
	private  static   final  int END_HOUR=24;

	@Autowired
	private JspkServiceImpl htbcServiceImpl;
	private int hour;

	/**
	 * 检测时间,如果凌晨就不进行投注,也是为反正别人进行异常数据监控
	 * @return
	 */
	private Boolean checkHour(){
		Calendar calendar = Calendar.getInstance();
		this.hour= calendar.get(Calendar.HOUR_OF_DAY);
		if(this.hour>=BIEGIN_HOUR&&hour<END_HOUR){
			LOGGER.info("当前时间[ {} ]在投注时间[ {} ~ {}]范围内 进行投注",hour,BIEGIN_HOUR,END_HOUR);
			return  true;
		}
		else {
			LOGGER.info("当前时间[ {} ]不在投注时间[ {} ~ {}]范围内 不进行投注",hour,BIEGIN_HOUR,END_HOUR);
			return false;
		}
	}

	/**
	 * 开始投注之前 为了避免每次开奖就投 故而 随机延迟 0.5到3分钟(10到50秒)
	 * 同时也是为了能更加准确的获取上一次投注是否中奖(有时候系统有延迟开奖)
	 */
	private void before()throws Exception{
		//单个最小化原子时间
		long atom=second*10;
		Random rd=new Random();
		int num= rd.nextInt(4)+1;
		LOGGER.info("延迟 {} 秒钟 ",num*10);
		Thread.sleep(atom*num);
	}

	@Autowired(required = false)
	private RedisService redisService;

	@Autowired
	private JspkServiceImpl jspkService;

	@Autowired
	private LuckDrawServiceImpl luckDrawService;
	public void  bet()throws Exception{
		LOGGER.info("");
		if(!checkHour()){
			return;
		}
		List<ConfigTaskDto> configs=jspkService.queryByTaskHour(this.hour);
		if(configs!=null&&configs.size()>0){
			before();
			for(ConfigTaskDto config:configs){
				UserBetConfigDto betConfigDto=new UserBetConfigDto(config.getToken(),config.getAccount());
				betConfigDto.setMode(config.getModel());
				betConfigDto.setZhu(config.getZhu());
				betConfigDto.setUserId(config.getUserId());
				betConfigDto.setTaskId(config.getTaskId());
				betConfigDto.setPower(config.getPower());
				//LOGGER.info("账户:{} 进行投注 基础配置为:{} ",config.getAccount(),betConfigDto.toString());
				new Thread(new LuckDrawJspkeRunnable(this.redisService,betConfigDto,luckDrawService)).start();
			}
		}
		else{
			LOGGER.info("当前时间[ {} ],没有满足条件的token,不进行投注",hour);
		}
	}



}
